package com.mall.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	/** 
	 * @description: 
	 * @param: 更新库存 
	 * @return:
	 * @author zhizhuke
	 * @date: 2022-01-20 16:55
	 */ 
	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {

		CreateOrderContext orderContext = (CreateOrderContext) context;
		List<CartProductDto> dtoList = orderContext.getCartProductDtoList();
		List<Long> productIds = orderContext.getBuyProductIds();

		if (CollectionUtils.isEmpty(productIds)){
			productIds = new ArrayList<>();
			for (CartProductDto cartProductDto : dtoList) {
				productIds.add(cartProductDto.getProductId());
			}
		}
		//锁定库存
		List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

		//异常判断
		if (CollectionUtils.isEmpty(stockList)){
			throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
					OrderRetCode.DB_EXCEPTION.getMessage()+"库存未初始化");
		}
		if (productIds.size()!=stockList.size()){
			throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
					OrderRetCode.DB_EXCEPTION.getMessage()+"部分商品库存未初始化");
		}
		//更新库存
		for (CartProductDto cartProductDto : dtoList) {
			Long itemId = cartProductDto.getProductId();
			Long productNum = cartProductDto.getProductNum();

			Stock stock = new Stock();
			stock.setItemId(itemId);
			//productNum不能超出限购数量
			Integer restrictCount = stockMapper.selectOne(stock).getRestrictCount();
			if (productNum>restrictCount){
				throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
						OrderRetCode.DB_EXCEPTION.getMessage()+"超出限购数量");
			}
			stock.setLockCount(productNum.intValue());
			stock.setStockCount(-productNum);
			stockMapper.updateStock(stock);
		}
        return true;
	}
}